package 链表反转;

import org.junit.Assert;

/**
 * 链表反转
 */
public class Solution {
    public static void main(String[] args) {

        // 1->2->3->4->5
        Node node5 = new Node(5, null);
        Node node4 = new Node(4, node5);
        Node node3 = new Node(3, node4);
        Node node2 = new Node(2, node3);
        Node node1 = new Node(1, node2);

        printLinkedList(node1);

        Node head = recursion(node1);

        Assert.assertNotNull(head);
        Assert.assertEquals(head.v, 5);

        printLinkedList(head);
    }

    /**
     * 递归法
     */
    private static Node recursion(Node node) {

        if (null == node.next) {
            return node;
        }

        Node head = recursion(node.next);

        node.next.next = node;
        node.next = null;

        return head;

    }

    /**
     * 循环法
     */
    private static Node reversed(Node head) {
        if (null == head || null == head.next) {
            return head;
        }

        Node prev = null, current = head, next = null;

        while (current != null) {

            next = current.next;

            current.next = prev;

            prev = current;

            current = next;

        }

        return prev;
    }

    private static void printLinkedList(Node head) {
        if (null == head) {
            return;
        }

        StringBuilder sb = new StringBuilder();
        do {
            sb.append(head.v);
            sb.append("->");
            head = head.next;
        } while (head != null);
        sb.deleteCharAt(sb.length() - 1).deleteCharAt(sb.length() - 1);
        System.out.println("linked = " + sb);
    }

}
